import axios, { AxiosError } from "axios";
import NProgress from "nprogress";
import showTip from "@/plugins/notice";

const ERROR_MSG = {
    ECONNABORTED: "请求超时,请稍后重试",
    ETIMEDOUT: "网络异常,请检查网络连接",
    ERR_NETWORK: "网络异常,请检查网络连接"
}
const HTTP_MSG = {
    401: "未授权",
    403: "未授权",
    404: "您所访问的资源不存在",
    500: "服务器异常,请联系管理员",
    DEFAULT: "服务器忙,请稍后重试"
}
// 请求前缀的统一定义  ==> 无协议请求地址会自动增加该默人前缀
axios.defaults.baseURL = "http://127.0.0.1:3002/api/";
axios.interceptors.request.use(
    function(config){
        NProgress.start();
        return config;
    }
)
axios.interceptors.response.use(
    function (response) {
        NProgress.done();
        // 统一成功处理
        // showTip("请求成功","","success")
        return response.data;
    },
    function (error) {
        NProgress.done();
        // console.log(111)
        let title = "运行错误,请联系管理员";
        // if (error instanceof axios.AxiosError) {
        if (error instanceof AxiosError) {
            let { status, code } = error.toJSON();
            if (status) {
                title = HTTP_MSG[status] || HTTP_MSG.DEFAULT;
            } else {
                title = ERROR_MSG[code];
            }
        }
        // alert(title)
        showTip("请求失败",title,"error")
        return Promise.reject(error);
    }
)

const loadUserList = function () {
    // return axios.get("http://127.0.0.1:3002/api/users")
    return axios.get("users")
}

export default {
    loadUserList
}